package com.rzhd.coursepatriarch.common.api.common;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.rzhd.coursepatriarch.common.base.BaseApplication;
import com.rzhd.coursepatriarch.common.beans.UserInfoBean;
import com.rzhd.coursepatriarch.common.constants.HttpConstants;
import com.rzhd.coursepatriarch.common.utils.CommonUtil;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * @author yql
 * Time: 2018/6/10.
 */
public class InterceptorUtil {

    public static String TAG = InterceptorUtil.class.getSimpleName();

    public static Cache getCache() {
        //设置缓存目录
        File cacheDirectory = new File(
                BaseApplication.getInstance().getCacheDir().getAbsolutePath(), HttpConstants.CACHE);
        Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024);
        return cache;
    }

    /**
     * 日志拦截器
     *
     * @return
     */
    public static HttpLoggingInterceptor getLogInterceptor() {
        return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.w(TAG, "HTTP_LOG:" + message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据级别
    }

    /**
     * 其他类型的拦截器
     *
     * @return
     */
    public static Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                //在这里可以做一些想做的事，比如token失效时，重新获取token
                //或者添加header等等
                Request newRequest = request.newBuilder()
                        .addHeader("Authorization", getToken() )
                        .addHeader("deviceType", "Android" )
                        .addHeader("appHeader", "parent" )
                        .build();
                return chain.proceed( newRequest );
            }
        };
    }

    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        SharedPreferences preferences = BaseApplication.getInstance().getSharedPreferences( BaseApplication.SHARED_DATA , Context.MODE_PRIVATE);
        String loginInfo = preferences.getString( "LOGIN_INFO", "");
        if (TextUtils.isEmpty(loginInfo)) {
            return "";
        }
        UserInfoBean.DataBean loginBean = JSON.parseObject(loginInfo, UserInfoBean.DataBean.class);
        if (loginBean == null ) {
            return "";
        }
        return loginBean.getToken();
    }

}
